package com.xuecheng.content.service.impl;

import com.xuecheng.base.exception.BusinessException;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.service.CourseCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    /**
     * 查询课程分类
     * @param id
     * @return
     */
    @Override
    public List<CourseCategoryTreeDto> queryCourseCategory(String id) {
        //校验
        if (StringUtils.isBlank(id)) {
            throw new BusinessException("参数为空");
        }
        //查询课程分类
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.courseCategoryQuery(id);
        //构建一个id与对应类型的哈希映射
        Map<String, CourseCategoryTreeDto> map = courseCategoryTreeDtos.stream()
                .filter(item -> !item.getId().equals(id))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //结果集
        List<CourseCategoryTreeDto> res = new ArrayList<>();
        //遍历courseCategoryTreeDtos
        courseCategoryTreeDtos.stream()
                .filter(item->!id.equals(item.getId()))
                .forEach(item->{
                    //如果是一级节点就放入结果集
                    if (id.equals(item.getParentid())) {
                        res.add(item);
                    }
                    //获取父节点
                    CourseCategoryTreeDto parentCourseCategoryDto = map.get(item.getParentid());
                    //判断当前节点是否有父节点
                    if (parentCourseCategoryDto != null) {
                        List<CourseCategoryTreeDto> childrenTreeNodes = parentCourseCategoryDto.getChildrenTreeNodes();
                        //判断子节点列表是否为null，null则创建
                        if (childrenTreeNodes == null) {
                            childrenTreeNodes = new ArrayList<>();
                            parentCourseCategoryDto.setChildrenTreeNodes(childrenTreeNodes);
                        }
                        //将item添加到其父节点的子节点列表中
                        childrenTreeNodes.add(item);
                    }
                });
        return res;
    }
}
